using System;
using System.Collections.Generic;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.SystemFacade.Contents;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;

namespace Fuse8.ContentManagementFramework.DataAccess
{
    public class CmsEntityNameMapper : DefaultEntityMappingConfiguratorForSuccessor
    {
        protected static Dictionary<Type, string> cache = new Dictionary<Type,string>();

        public override string GetEntityTableName(Type type)
        {
            if (cache.ContainsKey(type))
            {
                return cache[type];
            }

            string name;
            if (typeof(IContentItem).IsAssignableFrom(type))
            {
                var mappings = DependencyServiceLocator.Current.GetInstance<IContentEntityTypeMapper>().Mappings;
                if (!mappings.ContainsKey(type))
                {
                    throw new ArgumentOutOfRangeException("type",
                                                          string.Format(
                                                              "Type '{0}' is not mapped to any CMS content type. Please add mapping.",
                                                              type.FullName));
                }
                int contentTypeId = mappings[type];
                name = DependencyServiceLocator.Current.GetInstance<IContentSchemeBuilder>().GetDataEntityName(contentTypeId);
            }
            else
            {
                name = new DefaultEntityMappingConfigurator().GetEntityTableName(type);
                if (name.StartsWith("Cms"))
                {
                    name = name.Substring(3);
                }
                else
                {
                    name = null;
                }
            }

            cache[type] = name;
            
            return name;
        }

        public override string GetRelatedPropertyColumnName(Type type, string property)
        {
            //todo: think how to better deal with this
            if (typeof(ITrackingEntityObject).IsAssignableFrom(type) && property == "CreatedByUser")
            {
                return "CreatedBy";
            }

            if (typeof(ITrackingEntityObject).IsAssignableFrom(type) && property == "LastUpdatedByUser")
            {
                return "LastUpdatedBy";
            }
            return null;
        }        
    }
}